<!--
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-22 12:27:56
 * @LastEditTime: 2023-07-03 11:51:35
-->
<script setup lang="ts" name="DesignBase">
import { ArrowRight, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ikArray } from 'iking-utils'
import { IkingPicker } from 'iking-web-ui'
import '@/assets/styles/approve-center.scss'
import { EFlowFormType } from '../../../enum'
import { formApi } from '@/MainApp/apis/approve-center'

const route = useRoute()
const flowStore = useFlowStore()
const { groupList } = useGroupList()
const ruleBaseRef = ref<FormInstance>()
const baseForm = ref()

watch(() => flowStore.design?.base, () => {
  try {
    if (!flowStore.design?.base?.initiatorsName)
      flowStore.design.base.initiatorsName = '所有人'
  }
  catch (error) {

  }
  baseForm.value = flowStore.design.base
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入表单名称', trigger: 'blur' }],
  groupId: [{ required: true, message: '请选择所在分组', trigger: 'change' }],
  formId: [{ required: true, message: '请选择关联表单', trigger: 'change' }]
}

const { baseUrl } = useHttpUrl()
const token = useToken()
const showPicker = ref(false)
const refIkingPicker: Ref<null | { handClear: Function; }> = ref(null)
const c_type = {
  all: ['dep', 'user', 'role', 'post'],
  user: ['user']
}

watch(
  () => baseForm.value?.initiators,
  (val: any) => {
    // 同步基础配置和流程配置发起人信息
    flowStore.design.process.props.assignedUser = val
  }
)

const { msgError } = useMessage()
const echoData: Ref<any[]> = ref([])
const chooseType = ref(c_type.all)
const handChooseUser = (val?: string | null) => {
  chooseType.value = val ? c_type.user : c_type.all
  echoData.value = val ? baseForm.value.managers : baseForm.value.initiators
  nextTick(() => {
    showPicker.value = true
  })
}

onBeforeUnmount(() => {
  ruleBaseRef.value?.resetFields()
})

const JUST_FLOW = route.query.type === EFlowFormType.已有表单
const formList: Ref<{ name: string; id: string; }[]> = ref([])
const getFormList = async () => {
  const { msg, data, success } = await formApi.getFormList()
  if (!success) {
    formList.value = []
    msgError(msg)
    return
  }
  formList.value = data
}
if (JUST_FLOW)
  getFormList()

const handSelected = (val: { list: any[]; }) => {
  if (chooseType.value.length !== 1) {
    if (!val.list?.length) {
      baseForm.value.initiators = [{
        initiatorType: 'ALL'
      }]
      baseForm.value.initiatorsName = '所有人'
    }
    else {
      baseForm.value.initiators = val.list
      baseForm.value.initiatorsName = ikArray.listToString(
        val.list,
        'elementName',
        ', ',
        ''
      )
    }
  }
  else {
    if (!val.list?.length) {
      baseForm.value.managers = [{
        managerType: 'ALL'
      }]
      baseForm.value.managersName = ''
    }
    else {
      baseForm.value.managersName = ikArray.listToString(
        val.list,
        'elementName',
        ', ',
        ''
      )
      baseForm.value.managers = val.list
    }
  }
  refIkingPicker.value?.handClear()
}

const validate = () => {
  ruleBaseRef.value?.validate((valid, errors) => {
    if (valid)
      return true
    else return errors
  })
}

const handClear = (type: string) => {
  if (type === 'initiators') {
    baseForm.value.initiators = [{ initiatorType: 'ALL' }]
    baseForm.value.initiatorsName = '所有人'
  }
  else {
    baseForm.value.managers = [{ managerType: 'ALL' }]
    baseForm.value.managersName = ''
  }
}

const setFormName = async (id: string) => {
  const form = formList.value.find(item => item.id === id)
  if (form)
    baseForm.value.name = form.name
  const { msg, success, data } = await formApi.getFormWidgets(id)
  if (success) {
    flowStore.design.formItems = data
    // 同步基础配置和流程配置表单信息
    flowStore.designForm.widgetList = data
    flowStore.designForm.formConfig.formId = id
    flowStore.designForm.formConfig.formData = form
  }
  else {
    msgError(msg)
  }
}

// if (route.query?.isEdit) {

// }

const pickerApi = {
  methods: 'post',
  url: `${baseUrl}/server/component/pick/mix`,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    Authorization: token
  }
}

defineExpose({ validate, ruleBaseRef })
</script>

<template>
  <div v-if="baseForm">
    <el-card class="h-full overflow-y-auto iflow-content-main">
      <el-form
        ref="ruleBaseRef"
        label-position="top"
        :model="baseForm"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <div class="form-icon-picker">
          <el-form-item label="" prop="icon">
            <IkFlowIconPicker
              v-model="baseForm.icon"
              v-model:iconBackground="baseForm.iconBackground"
            />
          </el-form-item>
        </div>
        <!-- FORM_TYPE -->
        <el-form-item v-if="JUST_FLOW && !route.query.isEdit" label="关联表单" prop="formId">
          <el-select
            v-model="baseForm.formId"
            class="w-full"
            clearable
            placeholder="请选择关联表单"
            @change="setFormName"
          >
            <el-option
              v-for="item in formList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <IkFormItemTitle label="表单名称" title="最多50字" prop="name">
          <el-input
            v-model.trim="baseForm.name"
            placeholder="请输入表单名称"
            clearable
            maxlength="50"
          />
        </IkFormItemTitle>
        <el-form-item label="所在分组" prop="groupId">
          <el-select
            v-model="baseForm.groupId"
            class="w-full"
            clearable
            placeholder="请选择所在分组"
          >
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <IkFormItemTitle label="表单说明" title="最多100字" prop="remark">
          <el-input
            v-model.trim="baseForm.remark"
            :rows="5"
            clearable
            placeholder="请输入表单说明"
            maxlength="100"
            type="textarea"
            :show-word-limit="true"
          />
        </IkFormItemTitle>
        <IkFormItemTitle label="发起人" title="不选则默认所有人都可发起" prop="initiators">
          <el-input
            v-model="baseForm.initiatorsName"
            clearable
            placeholder="默认所有人"
            :suffix-icon="Plus"
            @clear="handClear('initiators')"
            @click="handChooseUser(null)"
          />
        </IkFormItemTitle>
        <el-form-item
          label="管理员"
          data-title="可以编辑模板并导出数据"
          prop="managers"
        >
          <el-input
            v-model="baseForm.managersName"
            clearable
            placeholder="有「审批设置」权限的所有用户"
            :suffix-icon="Plus"
            @clear="handClear('managers')"
            @click="handChooseUser('user')"
          />
        </el-form-item>
        <el-form-item>
          <el-button link type="primary" class="!p-0">
            权限管理
            <el-icon>
              <ArrowRight />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <IkingPicker
      ref="refIkingPicker"
      v-model="echoData"
      v-model:show="showPicker"
      :api="pickerApi"
      :choose-type="chooseType"
      :type-option="{ dep: 'DEPT', user: 'USER', role: 'ROLE', post: 'POST' }"
      :prop-option="{
        name: 'elementName',
        id: 'elementId',
        type: 'elementType',
      }"
      @ok="handSelected"
    />
  </div>
</template>

<style lang="scss" scoped>
.form-icon-picker {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}
</style>
